# app.py
import os
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail, Message
from config import Config

app = Flask(__name__)
app.config.from_object(Config)

db = SQLAlchemy(app)
mail = Mail(app)

# Event 模型定义
class Event(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.String(100))
    message = db.Column(db.String(200))

    def __repr__(self):
        return f'<Event {self.id} - {self.timestamp}>'

# 根路由，显示事件列表
@app.route('/')
def index():
    events = Event.query.all()
    return render_template('index.html', events=events)

# Webhook 路由，用于接收 Webhook 事件
@app.route('/webhook', methods=['POST'])
def webhook():
    data = request.get_json()

    # 获取提交的第一个 commit 数据
    commit = data.get('commits', [])[0]  # 假设 commits 数组至少有一个元素

    # 从 commit 数据中提取 timestamp 和 message
    timestamp = commit.get('timestamp')
    message = commit.get('message')

    # 创建一个新的 Event 对象并保存到数据库
    event = Event(timestamp=timestamp, message=message)
    db.session.add(event)
    db.session.commit()

    # 发送邮件通知
    send_email(event)

    return jsonify({"status": "success"}), 200

# 发送邮件的函数
def send_email(event):
    msg = Message(
        subject=Config.EMAIL_SUBJECT,
        recipients=[Config.EMAIL_RECIPIENT],
        body=f"事件时间戳: {event.timestamp}\n事件消息: {event.message}"
    )
    mail.send(msg)

if __name__ == '__main__':
    app.run(debug=True)
